package com.mk.plugin.generator;

import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.fileTemplates.FileTemplateUtil;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDirectory;
import com.mk.plugin.function.Functions;

import java.util.*;

public class ReducerGenerator {

    public void generator(Project project, Properties p, PsiDirectory dir, List<Functions> functionsList) {
        PsiDirectory reducersDirectory = dir.createSubdirectory("reducers");
        FileTemplate reducersTemplate = FileTemplateManager.getInstance(project).getInternalTemplate("reducers");

        Map<String, Object> properties = new HashMap<>(); // 拷贝新的properties
        for (Object o : p.keySet()) {
            properties.put((String) o, p.get(o));
        }

        Set<String> reducerSwitches = new HashSet<>();
        Set<String> reducerFunctions = new HashSet<>();
        Set<String> reducerInitState = new HashSet<>();
        Set<String> reducerSearchConditionInitState = new HashSet<>();
        Set<String> reducerImportStatements = new HashSet<>();

        boolean needPagination = false;

        for (Functions f : functionsList) {
            reducerSwitches.add(f.getReducerSwitches(properties));
            reducerFunctions.add(f.getReducerFunctions(properties));
            reducerInitState.addAll(f.getReducerInitState(properties));
            reducerSearchConditionInitState.addAll(f.getSearchConditionInitState(properties));
            reducerImportStatements.addAll(f.getReducerImportStatement());

            if (f.getNeedComponent().contains("Pagination")) {
                needPagination = true;
            }
        }

        properties.put("reducerSwitches", reducerSwitches);
        properties.put("reducerFunctions", reducerFunctions);
        properties.put("reducerInitState", reducerInitState);
        properties.put("reducerSearchConditionInitState", reducerSearchConditionInitState);
        properties.put("reducerImportStatements", reducerImportStatements);
        properties.put("needPagination", needPagination);

        try {
            FileTemplateUtil.createFromTemplate(reducersTemplate, properties.get("underscore_name") + ".reducers.tsx", properties, reducersDirectory, getClass().getClassLoader());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}
